package cn.jnetty.ioc.definition;
import cn.jnetty.api.exception.JnettyIocException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author 猪哥亮
 * @email 1030681978@qq.com
 * @date 2020/4/3 18:50
 * 描述：
 */
public class JDefaultBeanDefinitionFactory {
    private static class Singleton{
        public static final JDefaultBeanDefinitionFactory INSTANCE = new JDefaultBeanDefinitionFactory();
    }
    public static JDefaultBeanDefinitionFactory getInstance(){
        return Singleton.INSTANCE;
    }
    private Map<Class<?>, Object> clazzMapping = new HashMap<>();
    private Map<String,Object> beanNameMapping = new HashMap<>();
    public void put(String beanName,Class<?> clazz,Object bean){
        clazzMapping.put(clazz,bean);
        if(beanName != null && !beanName.equals("")){
            beanNameMapping.put(beanName,bean);
        }else {
            String first = clazz.getSimpleName().substring(0, 1);
            first = first.toLowerCase();
            String str = clazz.getSimpleName().substring(1,clazz.getSimpleName().length());
            first += str;
            //默认首字母小写并删除Impl
            if(first.endsWith("Impl")){
                first = first.substring(0,first.length() - 4);
            }
            beanNameMapping.put(first,bean);
        }
    }

    public Object getBean(String beanName){
        return  beanNameMapping.getOrDefault(beanName,null);
    }
    public Object getBean(Class<?> clazz){
        List<Object> listByType = getListByType(clazz);
        if(listByType.size() == 0){
            throw new JnettyIocException("获取JavaBean->{0}异常，容器中没有这javaBean",clazz.getName());
        }
        if(listByType.size() > 1){
            throw new JnettyIocException("获取JavaBean->{0}异常，容器中有多个javaBean不知道要获取那个bean",clazz.getName());
        }
        return  listByType.get(0);
    }
    public List<Object> getListByType(Class<?> clazz){
        List<Object> list = getList();
        List<Object> result = new ArrayList<>();
        for (Object o1 : list) {
            if(o1.getClass() == clazz || clazz.isAssignableFrom(o1.getClass())){
                result.add(o1);
            }
        }
        return result;
    }
    public List<Object> getList(){
        return new ArrayList<>(clazzMapping.values());
    }

    public static void main(String[] args) {
        JDefaultBeanDefinitionFactory factory = new JDefaultBeanDefinitionFactory();

    }
}
